package com.helu.lubike.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;

import com.helu.lubike.model.BTBean;
import com.helu.lubike.adapter.BTMainRCVAdapter;
import com.helu.lubike.utils.BluetoothManager;
import com.helu.lubike.R;
import com.helu.lubike.utils.Utils;
import com.helu.lubike.databinding.ActivityBtMainBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author helu  17-2-8 上午8:58
 * @description
 */

public class BluetoothMainActivity extends AppCompatActivity {

    private static final String MSG = "BluetoothMainActivity";
    private ActivityBtMainBinding binding;
    private List<BTBean> devices_list = new ArrayList<>();
    private BluetoothAdapter mBluetoothAdapter;
    private BTMainRCVAdapter mAdapter;
    private boolean isDiscovering;
    /**
     * 手动取消了蓝牙搜索
     */
    private boolean isFromManCancel;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 获得已经搜索到的蓝牙设备
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
                BTBean btBean = new BTBean(rssi, device);
                if (device.getName() != null && device.getName().startsWith(getString(R.string.bikeNamePrifix))) {     //如果是小路单车的蓝牙信号
                    devices_list.add(btBean);
                    mAdapter.addData(BluetoothMainActivity.this, btBean);
                    toDisplayList();
                }

            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {  //搜索完成
                isDiscovering = false;
                if (isFromManCancel) {
                    isFromManCancel = false;
                } else {
                    Utils.showToast(BluetoothMainActivity.this, "搜寻完成了!");
                }
                toDisplayList();
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                devices_list.clear();
                mAdapter.clearAllData();
            }
        }
    };


    /**
     * 显示数据
     */
    public void toDisplayList() {
        binding.loading.setVisibility(View.GONE);
        if (binding.swipeRefreshWidget.isRefreshing()) {
            binding.swipeRefreshWidget.setRefreshing(false);
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_bt_main, null, false);
        setContentView(binding.getRoot());
        initView();
        initListener();
        initData();
    }


    private void initView() {
        binding.swipeRefreshWidget.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        binding.rcv.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        binding.rcv.setItemAnimator(new DefaultItemAnimator());
        binding.rcv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter = new BTMainRCVAdapter();
        binding.rcv.setAdapter(mAdapter);

        mAdapter.setEmptyView(binding.emptyView);
    }


    /**
     * 列表有item被点击了,关闭搜索
     */
    public void notifyHasItemClick() {
        isFromManCancel = true;
    }

    private void initListener() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                startBTDiscovery();
            }
        });
    }


    /**
     * 开始蓝牙扫描
     */
    private void startBTDiscovery() {
        // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
        if (isDiscovering) {
            Utils.showToast(this, "上次搜寻还未结束,请稍候..");
        } else {
            mBluetoothAdapter.startDiscovery();
            isDiscovering = true;
        }

    }

    private void initData() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 获取所有已经绑定的蓝牙设备
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        if (devices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : devices) {
                Log.d(MSG, "已经绑定的有:" + bluetoothDevice.getName() + "," + bluetoothDevice.getAddress() + ",getBondState" + bluetoothDevice.getBondState());
            }
        }
        // 注册用以接收到已搜索到的蓝牙设备的receiver
        IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, mFilter);

        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, mFilter);

        // 注册搜索开始时的receiver
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver, mFilter);

        if (!BluetoothManager.isBluetoothEnabled()) {
            boolean cannot = BluetoothManager.turnOnBluetooth();
            if (!cannot) { //如果打开蓝牙失败
                Utils.showToast(this, "请先打开蓝牙开关");
                openBTSetting();
            } else {
                Log.d(MSG, "打开蓝牙后开始搜索蓝牙设备");
                startBTDiscovery();
            }
        } else {
            Log.d(MSG, "已经打开蓝牙后开始搜索蓝牙设备");
            // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
            startBTDiscovery();
        }

    }


    private void openBTSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册
        unregisterReceiver(mReceiver);
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
    }
}
